package com.sunxboy.platform.option;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;

public class CommandLineArgumentProcessor {
    private static final Logger LOG = Logger.getLogger(CommandLineArgumentProcessor.class);
    private final CommandLineOptions commandLineOptions = new CommandLineOptions();
    private final String[] remainingArgs;

    public CommandLineArgumentProcessor(final String[] args) {
        this.remainingArgs = processArguments(args);
    }

    public String[] processArguments(String[] args) {

        List<String> unhandledArgs = new LinkedList<String>();
        for (int argNo = 0; argNo < args.length; argNo++) {
            String argument = args[argNo];
            if (argument.equals("--")) {
                return Arrays.copyOfRange(args, argNo, args.length);
            }

            if (argument.startsWith("--core:")) {
                Assert.isTrue((argNo + 1) < args.length, "Options " + argument + " requires a value parameter that is missing");

                final String value = args[++argNo];
                Options option = Options.toOption(argument);
                if (option != null) {
                    option.processValue(commandLineOptions, value);
                }
                else {
                    LOG.warn(String.format("Option %s and value %s are not handled", option, value));
                }

            }
            else {
                unhandledArgs.add(args[argNo]);
            }
        }

        return unhandledArgs.toArray(new String[] {});
    }

    public String[] getArguments() {
        return remainingArgs;
    }

    public CommandLineOptions getOptions() {
        return commandLineOptions;
    }
}
